/**
 * 服务列表页面
 *
 * 这个页面展示了：
 * 1. 服务列表展示
 * 2. 分类筛选
 * 3. 价格排序
 * 4. 推荐服务标识
 */
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { useServices } from '@/hooks/useServices';
import Navbar from '@/components/Navbar';

export default function Services() {
  const [selectedCategory, setSelectedCategory] = useState('');
  const [sortBy, setSortBy] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 12;

  // 获取服务数据
  const {
    data: servicesData,
    isLoading,
    error
  } = useServices({
    category: selectedCategory,
    sort_by: sortBy,
    page: currentPage,
    size: pageSize,
    active_only: true
  });

  // 服务分类
  const categories = [
    '环境影响评价',
    '污染治理工程',
    '生态环境修复',
    '环境监测检测',
    '环保咨询服务'
  ];

  // 排序选项
  const sortOptions = [
    { value: '', label: '默认排序' },
    { value: 'price_asc', label: '价格从低到高' },
    { value: 'price_desc', label: '价格从高到低' },
    { value: 'name_asc', label: '名称A-Z' },
    { value: 'name_desc', label: '名称Z-A' }
  ];

  // 格式化价格
  const formatPrice = (price?: number) => {
    if (!price) return '面议';
    if (price >= 10000) {
      return `${(price / 10000).toFixed(1)}万元起`;
    }
    return `${price.toLocaleString()}元起`;
  };

  // 处理分类筛选
  const handleCategoryChange = (category: string) => {
    setSelectedCategory(category === selectedCategory ? '' : category);
    setCurrentPage(1);
  };

  // 处理排序
  const handleSortChange = (sort: string) => {
    setSortBy(sort);
    setCurrentPage(1);
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <Navbar />
      {/* 页面头部 */}
      <div className="bg-white border-b">
        <div className="container mx-auto px-4 py-8">
          <div className="text-center">
            <h1 className="text-3xl md:text-4xl font-bold text-gray-900 mb-4">
              业务范围
            </h1>
            <p className="text-lg text-gray-600 max-w-2xl mx-auto">
              专业的环境工程咨询服务，为您提供全方位的环保解决方案
            </p>
          </div>
        </div>
      </div>

      <div className="container mx-auto px-4 py-8">
        <div className="flex flex-col lg:flex-row gap-8">
          {/* 侧边栏 */}
          <div className="lg:w-1/4">
            {/* 分类筛选 */}
            <div className="bg-white rounded-lg shadow-md p-6 mb-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">服务分类</h3>
              <div className="space-y-2">
                <button
                  type="button"
                  onClick={() => handleCategoryChange('')}
                  className={`w-full text-left px-3 py-2 rounded-lg transition-colors ${
                    selectedCategory === ''
                      ? 'bg-blue-100 text-blue-800'
                      : 'text-gray-700 hover:bg-gray-100'
                  }`}
                >
                  全部服务
                </button>
                {categories.map((category) => (
                  <button
                    key={category}
                    type="button"
                    onClick={() => handleCategoryChange(category)}
                    className={`w-full text-left px-3 py-2 rounded-lg transition-colors ${
                      selectedCategory === category
                        ? 'bg-blue-100 text-blue-800'
                        : 'text-gray-700 hover:bg-gray-100'
                    }`}
                  >
                    {category}
                  </button>
                ))}
              </div>
            </div>

            {/* 排序选项 */}
            <div className="bg-white rounded-lg shadow-md p-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">排序方式</h3>
              <div className="space-y-2">
                {sortOptions.map((option) => (
                  <button
                    key={option.value}
                    type="button"
                    onClick={() => handleSortChange(option.value)}
                    className={`w-full text-left px-3 py-2 rounded-lg transition-colors ${
                      sortBy === option.value
                        ? 'bg-blue-100 text-blue-800'
                        : 'text-gray-700 hover:bg-gray-100'
                    }`}
                  >
                    {option.label}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* 主要内容 */}
          <div className="lg:w-3/4">
            {/* 结果统计 */}
            {!isLoading && !error && servicesData && (
              <div className="flex items-center justify-between mb-6">
                <p className="text-gray-600">
                  共找到 <span className="font-semibold text-gray-900">{servicesData.total}</span> 项服务
                </p>
                <div className="flex items-center space-x-4">
                  <span className="text-sm text-gray-500">显示方式：</span>
                  <div className="flex items-center space-x-2">
                    <button
                      type="button"
                      className="p-2 border border-gray-300 rounded-lg bg-blue-50 text-blue-600"
                      aria-label="网格视图"
                    >
                      <i className="fa-solid fa-th-large"></i>
                    </button>
                    <button
                      type="button"
                      className="p-2 border border-gray-300 rounded-lg text-gray-400"
                      aria-label="列表视图"
                    >
                      <i className="fa-solid fa-list"></i>
                    </button>
                  </div>
                </div>
              </div>
            )}

            {/* 加载状态 */}
            {isLoading && (
              <div className="grid md:grid-cols-2 xl:grid-cols-3 gap-6">
                {[...Array(6)].map((_, index) => (
                  <div key={index} className="bg-white rounded-lg shadow-md overflow-hidden animate-pulse">
                    <div className="h-48 bg-gray-200"></div>
                    <div className="p-6">
                      <div className="h-4 bg-gray-200 rounded w-1/4 mb-2"></div>
                      <div className="h-6 bg-gray-200 rounded w-3/4 mb-3"></div>
                      <div className="h-4 bg-gray-200 rounded w-full mb-2"></div>
                      <div className="h-8 bg-gray-200 rounded w-1/3"></div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* 错误状态 */}
            {error && (
              <div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
                <i className="fa-solid fa-exclamation-triangle text-red-500 text-2xl mb-4"></i>
                <p className="text-red-700">加载服务失败，请稍后重试</p>
              </div>
            )}

            {/* 服务列表 */}
            {!isLoading && !error && servicesData && (
              <>
                {servicesData.items.length > 0 ? (
                  <>
                    <div className="grid md:grid-cols-2 xl:grid-cols-3 gap-6 mb-8">
                      {servicesData.items.map((service) => (
                        <Link
                          key={service.id}
                          to={`/services/${service.id}`}
                          className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow group"
                        >
                          {/* 服务图标/图片 */}
                          <div className="relative h-48 bg-gradient-to-br from-blue-50 to-blue-100 flex items-center justify-center">
                            {service.icon_url ? (
                              service.icon_url.startsWith('fa-') ? (
                                <i className={`fa-solid ${service.icon_url} text-blue-600 text-4xl group-hover:scale-110 transition-transform`}></i>
                              ) : (
                                <img
                                  src={service.icon_url}
                                  alt={service.name}
                                  className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                                  onError={(e) => {
                                    const target = e.target as HTMLImageElement;
                                    target.style.display = 'none';
                                    target.parentElement!.innerHTML = '<i class="fa-solid fa-cog text-blue-600 text-4xl"></i>';
                                  }}
                                />
                              )
                            ) : (
                              <i className="fa-solid fa-cog text-blue-600 text-4xl group-hover:scale-110 transition-transform"></i>
                            )}

                            {/* 推荐标识 */}
                            {service.is_featured && (
                              <div className="absolute top-3 right-3">
                                <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-orange-500 text-white">
                                  <i className="fa-solid fa-star mr-1"></i>
                                  推荐
                                </span>
                              </div>
                            )}
                          </div>

                          {/* 服务内容 */}
                          <div className="p-6">
                            <div className="flex items-center justify-between mb-3">
                              <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                {service.category}
                              </span>
                            </div>

                            <h3 className="text-lg font-semibold text-gray-900 mb-3 line-clamp-2 group-hover:text-blue-600 transition-colors">
                              {service.name}
                            </h3>

                            {service.description && (
                              <p className="text-gray-600 text-sm line-clamp-3 mb-4">
                                {service.description}
                              </p>
                            )}

                            <div className="flex items-center justify-between">
                              <div>
                                <span className="text-lg font-bold text-blue-600">
                                  {formatPrice(service.price)}
                                </span>
                              </div>
                              <div className="text-blue-600 group-hover:translate-x-1 transition-transform">
                                <i className="fa-solid fa-arrow-right"></i>
                              </div>
                            </div>
                          </div>
                        </Link>
                      ))}
                    </div>

                    {/* 分页 */}
                    {servicesData.total > pageSize && (
                      <div className="flex justify-center">
                        <div className="flex items-center space-x-2">
                          <button
                            type="button"
                            onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                            disabled={currentPage === 1}
                            className="px-3 py-2 border border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
                            aria-label="上一页"
                          >
                            <i className="fa-solid fa-chevron-left"></i>
                          </button>

                          <span className="px-4 py-2 text-sm text-gray-700">
                            第 {currentPage} 页，共 {Math.ceil(servicesData.total / pageSize)} 页
                          </span>

                          <button
                            type="button"
                            onClick={() => setCurrentPage(Math.min(Math.ceil(servicesData.total / pageSize), currentPage + 1))}
                            disabled={currentPage >= Math.ceil(servicesData.total / pageSize)}
                            className="px-3 py-2 border border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
                            aria-label="下一页"
                          >
                            <i className="fa-solid fa-chevron-right"></i>
                          </button>
                        </div>
                      </div>
                    )}
                  </>
                ) : (
                  <div className="text-center py-12">
                    <i className="fa-solid fa-cogs text-gray-400 text-6xl mb-4"></i>
                    <h3 className="text-xl font-semibold text-gray-900 mb-2">暂无服务</h3>
                    <p className="text-gray-600">
                      {selectedCategory ? '该分类下暂无服务项目' : '还没有发布任何服务'}
                    </p>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}